package org.gdkm.springbootxiangmushizhan.controller.admin;

import org.gdkm.springbootxiangmushizhan.domain.vo.CategoryAdminVO;
import org.gdkm.springbootxiangmushizhan.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/category")
public class CategoryAdminController {
    @Autowired
    private ICategoryService categoryService;

    // 分类管理页面，支持条件查询
    @GetMapping("")
    public String list(@RequestParam(value = "name", required = false) String name, HttpServletRequest request) {
        List<CategoryAdminVO> categories = (name == null || name.isEmpty()) ?
                categoryService.selectAllCategories() : categoryService.selectCategoriesByName(name);
        request.setAttribute("categories", categories);
        request.setAttribute("searchName", name);
        return "back/category_list";
    }

    // 新增分类
    @PostMapping("/add")
    @ResponseBody
    public String add(@RequestParam String name, @RequestParam(required = false) String description) {
        Date now = new Date();
        categoryService.insertCategory(name, description, now, now);
        return "ok";
    }

    // 编辑分类
    @PostMapping("/edit")
    @ResponseBody
    public String edit(@RequestParam Integer id, @RequestParam String name, @RequestParam(required = false) String description) {
        Date now = new Date();
        categoryService.updateCategory(id, name, description, now);
        return "ok";
    }

    // 删除分类
    @PostMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam Integer id) {
        categoryService.deleteCategory(id);
        return "ok";
    }

    // 根据id查单个分类（编辑弹窗回显）
    @GetMapping("/info")
    @ResponseBody
    public CategoryAdminVO info(@RequestParam Integer id) {
        return categoryService.selectCategoryById(id);
    }
} 